
// api/http.js
import axios from 'axios'
import { showMessage } from '@/utils/message'
import { getToken, removeToken } from '@/utils/storage'

// 创建 axios 实例
const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 添加 token 到请求头
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 如果是 FormData，修改 Content-Type
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    
    console.log('请求配置:', config)
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    // 处理响应数据
    const { data } = response
    
    // 根据后端返回结构调整
    if (data.code === 200) {
      return data.data
    } else {
      // 业务错误
      showMessage(data.message || '操作失败', 'error')
      return Promise.reject(new Error(data.message))
    }
  },
  (error) => {
    // 处理 HTTP 错误
    const { response } = error
    
    if (response) {
      switch (response.status) {
        case 401:
          // token 失效，清除本地token并跳转到登录页
          removeToken()
          window.location.href = '/login'
          showMessage('登录已过期，请重新登录', 'error')
          break
        case 403:
          showMessage('没有权限访问', 'error')
          break
        case 404:
          showMessage('请求资源不存在', 'error')
          break
        case 500:
          showMessage('服务器内部错误', 'error')
          break
        default:
          showMessage(response.data?.message || '网络错误', 'error')
      }
    } else {
      showMessage('网络连接失败，请检查网络', 'error')
    }
    
    return Promise.reject(error)
  }
)

// 通用请求方法封装
export const request = {
  get: (url, params = {}) => http.get(url, { params }),
  post: (url, data = {}) => http.post(url, data),
  put: (url, data = {}) => http.put(url, data),
  delete: (url, params = {}) => http.delete(url, { params }),
  upload: (url, file, data = {}) => {
    const formData = new FormData()
    formData.append('file', file)
    Object.keys(data).forEach(key => {
      formData.append(key, data[key])
    })
    return http.post(url, formData)
  }
}

export default http